package com.example.demo.interceptor;

import com.example.demo.controller.DashboardVerifyController;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Component
public class DashboardVerificationInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 检查会话中是否存在验证标记
        if (!DashboardVerifyController.isDashboardVerified(session)) {
            // 如果不存在，重定向到验证页面
            String encodedRedirectUrl = URLEncoder.encode(requestURI, StandardCharsets.UTF_8.toString());
            response.sendRedirect("/verify-dashboard?redirectUrl=" + encodedRedirectUrl);
            return false;
        }
        
        // 如果验证通过，允许继续访问
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 不需要额外处理
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 不需要额外处理
    }
} 